<?php

namespace app\admin\controller\mox\inherit\story;

use app\common\controller\Backend;
use think\Db;

/**
 * 木偶戏文化传承故事
 *
 * @icon fa fa-circle-o
 */
class Info extends Backend
{

    /**
     * Info模型对象
     * @var \app\admin\model\mox\inherit\story\Info
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mox\inherit\story\Info;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)
                ->each(function ($item, $key) {
                    $label = explode(',', $item['label_id']);
                    $item['label'] = model('app\admin\model\mox\inherit\story\Label')->where('id', 'in', $label)->select();
                    $relatedpersons = explode(',', $item['related_persons']);
                    $item['relatedpersons'] = model('app\admin\model\mox\inherit\Character')->where('id', 'in', $relatedpersons)->select();
                    $item['chapter_num'] = model('app\admin\model\mox\inherit\story\Chapter')->where('s_id', $item['id'])->count();
                    $item['zi_num'] = model('app\admin\model\mox\inherit\story\Chapter')
                        ->where('s_id', $item['id'])
                        ->sum('content_num');
                });
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['user_id'] = $this->auth->user_id;
                $params['create_time'] = time();
                $this->model->save($params);
                $this->success();
            } else {
                $this->error();
            }
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['user_id'] = $this->auth->user_id;
                $params['update_time'] = time();
                $this->model->save($params, ['id' => $ids]);
                $this->success();
            } else {
                $this->error();
            }
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 多级联动，选择故事和章节
     */
    public function cxselect()
    {
        $list = Db::name('mox_inherit_story_info')->field('id as value, title as name')->select();
        $this->success('', '', $list);
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 获取文件夹路径
                    $saveDir = $path = ROOT_PATH;
                    $dirPath = $saveDir . "public/uploads/mox_story/" . $v->id;
                    // 删除章节
                    $chapter_delete = model('app\admin\model\mox\inherit\story\Chapter')->where('s_id', $v['id'])->delete();
                    if ($chapter_delete) {
                        // 删除章节文件夹
                        $this->deleteDirectory($dirPath);
                    }
                    // 删除故事
                    $result = model('app\admin\model\mox\inherit\story\Info')->where('id', $v['id'])->delete();
                }
                Db::commit();
                if ($result) {
                    $this->success();
                } else {
                    $this->error(__('No rows were deleted'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }
    /**
     * 删除非空文件夹（递归）
     * @param string $dirPath 文件夹路径
     * @return bool 是否删除成功
     */
    public function deleteDirectory($dirPath)
    {
        if (!is_dir($dirPath)) {
            return false;
        }

        $items = scandir($dirPath);
        foreach ($items as $item) {
            if ($item == '.' || $item == '..') {
                continue;
            }
            $itemPath = $dirPath . DIRECTORY_SEPARATOR . $item;
            if (is_dir($itemPath)) {
                $this->deleteDirectory($itemPath); // 正确调用方式
            } else {
                unlink($itemPath);
            }
        }
        return rmdir($dirPath);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}
